package org.chen.aao.ai.controller;

import lombok.RequiredArgsConstructor;
import org.chen.aao.ai.service.ITranslateService;
import org.chen.aao.common.ai.dto.TranslateHistoryResponse;
import org.chen.aao.common.ai.dto.TranslateRequest;
import org.chen.aao.common.ai.dto.TranslateResponse;
import org.chen.aao.common.annotation.RateLimit;
import org.chen.aao.common.exception.BusinessException;
import org.chen.aao.common.response.Result;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequiredArgsConstructor
public class TranslateController {
    private final ITranslateService translateService;

    @PostMapping("/translate")
    @RateLimit(key = "translate", count = 200, time = 3600)
    public Result<TranslateResponse> translate(@Validated @RequestBody TranslateRequest request,
                                               HttpServletRequest httpRequest) {
        Long userId = getUserId(httpRequest);
        return Result.success(translateService.translate(request, userId));
    }

    @GetMapping("/translate/history")
    public Result<TranslateHistoryResponse> getTranslateHistory(@RequestParam(value = "page", defaultValue = "1") int page,
                                                                @RequestParam(value = "size", defaultValue = "20") int size,
                                                                HttpServletRequest httpRequest) {
        Long userId = getUserId(httpRequest);
        return Result.success(translateService.getTranslateHistory(userId, page, size));
    }

    private Long getUserId(HttpServletRequest request) {
        String userIdHeader = request.getHeader("X-User-Id");
        if (userIdHeader == null || userIdHeader.trim().isEmpty()) {
            throw new BusinessException("用户未登录");
        }
        try {
            return Long.valueOf(userIdHeader);
        } catch (NumberFormatException e) {
            throw new BusinessException("用户ID格式错误");
        }
    }
}
